<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/

if (!defined ('EXPLAY')) exit;


$number = 30;
$start = 0;
if (isset($_GET['id'])) $id = intval ($_GET['id']);
if (!empty($_GET['page'])) $start = (intval ($_GET['page']) - 1) * $number;

$errors = array ();

if (isset($_GET['delete'])) {
	$delete = $db->query ("DELETE FROM ".DB_PEREFIX."_messages WHERE mes_id = '".intval($_GET['delete'])."' AND mes_user = '".$GLOBAL_USER['user_id']."'");
	
	site_message ('Сообщение удалено!');
}

// Вывод сообщения
if (isset($_GET['id'])) {
	$get = $db->query ("SELECT *, u.user_name, u.user_login FROM ".DB_PEREFIX."_messages AS m
		LEFT JOIN (SELECT user_id, user_name, user_login FROM ".DB_PEREFIX."_users) AS u ON u.user_id = m.mes_author
		WHERE mes_id = '$id' AND mes_user = ".User::$properties['user_id']);
	
	if ($db->num_rows ($get) == 1) {
		
		$db->query ("UPDATE ".DB_PEREFIX."_messages SET mes_read = 'old' WHERE mes_id = '$id'");
	
		$message = $db->fetch_array($get);
			
		Templater::load ('messages/view.tpl');
			
		$message['mews_date'] = format_time($message['mews_date']);
		$message['mes_body'] = n2br (replace_symbols ($message['mes_body']));
		$subject = urlencode($message['mes_header']);
		
		Templater::set_var ('message', $message);
		Templater::set_var ('subject', $subject);
		
		if (!isset_friend($message['mes_author'])) {
			$not_friend = Templater::display_part ('not_friend', false);
		} else {
			$not_friend = '';
		}
		
		Templater::set_var ('not_friend', $not_friend);
		
		print Templater::display_part ('main');
			
	}
	else error_404 ();
	
	come_back ('персональным сообшениям', '/messages/');
}

// Написать сообщение
if ($_GET['cat'] == 'write') {
	if (isset($_POST['submit'])) {
		$user = intval ($_POST['user']);
		$header = strip_tags ($_POST['header']);
		$body = strip_tags(htmlspecialchars($_POST['body'], ENT_QUOTES));
		$body = htmlspecialchars($body);
		$body = replace_symbols ($body);
		$error = '';
	
		if (!isset_friend($user)) $errors['user'] = 'Этого пользователя нет в списках ваших друзей';
		if ($user == 0) $errors['user'] = 'Выберите получателя';
		if ($header == '') $header = '&lt;без темы&gt;';
		if ($body == '') $errors['body'] = 'Заполните текст сообщения';
		
		if ($error == '' && count ($errors) == 0) {
			
			$send = $db->query ("INSERT INTO ".DB_PEREFIX."_messages VALUES (0, '$user', '".User::$properties['user_id']."', '$header', '$body', '".time()."', 'new')");
			$id = mysql_insert_id ();
			
			site_message ('Сообщение было отправлено!');

			$usr = $db->fetch_array ($db->query ("SELECT user_name, user_email FROM ".DB_PEREFIX."_users WHERE user_id = '$user'"));
				
			$info = array ();
			$info['user_name'] = $usr['user_name'];
			$site = $_SERVER['HTTP_HOST'];
			$info['url'] = 'http://'.$site.'/messages/'.$id.'.html';
			
			Templater::set_var ('info', $info);
			$mail = Templater::display ('mail/message.tpl');
				
			if (!is_localhost ()) {
				mail (
					$usr['user_name'].' <'.$usr['user_email'].'>',
					"Новое сообщение от ".User::$properties['user_name'],
					$mail,
					"From: ".$SITE['site_name']." <".$SITE['site_email'].">".
					"\nContent-Type: text/html; charset=\"utf-8\"".
					"\nContent-Transfer-Encoding: 8bit\n"
				);
			}
			
		}
		elseif ($error != '') site_error ($error);
	}
		
	if (isset($_GET['subject']))
		$title = 'Re: '.htmlspecialchars (urldecode($_GET['subject']), ENT_QUOTES);
	else
		$title = htmlspecialchars ($_POST['header'], ENT_QUOTES);
	
	CORE::set_page_title ('Новое сообщение &mdash; '.$SITE['site_name']);
	
	whrite_message ($user_name, $title);
	come_back ('персональным сообшениям', '/messages/');
}

// Вывод списка сообщений
elseif (!isset($_GET['id'])) {
	simple_table ('<a href="/messages/write/">Написать персональное сообщение пользователю</a>');
	
	$total = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_messages WHERE mes_user = '".$GLOBAL_USER['user_id']."'"));
	$new = $db->num_rows ($db->query ("SELECT mes_id FROM ".DB_PEREFIX."_messages WHERE mes_user = '".$GLOBAL_USER['user_id']."' && mes_read = 'new'"));
	$sender = $db->num_rows ($db->query ("SELECT mes_id FROM ".DB_PEREFIX."_messages WHERE mes_author = '".$GLOBAL_USER['user_id']."'"));
	
	$statist = "Всего сообщеий: $total | Новых: $new | Отправленных: $sender";
	past_table ('Статистика', $statist);
	
	$get = $db->query ("SELECT m.*, u.user_name, u.user_login FROM ".DB_PEREFIX."_messages AS m
		LEFT JOIN (SELECT user_id, user_name, user_login FROM ".DB_PEREFIX."_users) AS u ON m.mes_author = u.user_id
		WHERE mes_user = '".$GLOBAL_USER['user_id']."' ORDER BY mes_id DESC LIMIT $start, $number");
	
	if ($db->num_rows ($get) > 0) {
		
		$items = '';
		Templater::load ('messages/list_view.tpl');
		
		while ($message = $db->fetch_array ($get)) {
			
			if ($readed == 'new') $header_ = "<b>$header</b>";
			if ($readed == 'old') $header_ = $header;
			
			$answer_link = '';
			if (isset_friend($message['mes_author'])) $answer_link = '<a href="/messages/write/?to='.$message['mes_author'].'&subject='.urlencode($message['mes_header']).'">Ответить</a> | ';
			
			$message['mes_date'] = format_time ($message['mews_date']);
			
			Templater::set_var ('message', $message);
			Templater::set_var ('answer_link', $answer_link);
			
			$list .= ($message['mes_read'] == 'new')
						? Templater::display_part ('item_new')
						: Templater::display_part ('item_readed');
		}
		
		Templater::set_var ('list', $list);
		$table = Templater::display_part ('main');
		past_table ('Персональные сообщения', $table);
		
		if ($total > $number) print past_pages($start, $number, $total, '/messages/');
		
		unset ($items);
		
	}
	else site_error ('Нет входящих сообщений!');
	
}



function whrite_message ($user, $title) {
	global $SITE, $db, $errors;
	
	//
	// Form
	//
	include $_SERVER['DOCUMENT_ROOT'].'/engine/forms.class.php';
	
	$form = new explayForm ('Персональное сообщение пользователю', '/messages/write/', 'post', 'record');
	
	$item = $form->new_item ('select');
	$item->label ('Получатель');
	$item->name ('user');
	if (isset ($errors['user'])) $item->error ($errors['user']);
	
	$get = $db->query ("SELECT friend, f.user_name FROM ".DB_PEREFIX."_friends AS u
		LEFT JOIN (SELECT user_id, user_name FROM ".DB_PEREFIX."_users) AS f ON f.user_id = u.friend
		WHERE user = ".User::$properties['user_id']." ORDER BY f.user_name");

	if ($db->num_rows ($get) > 0) {
	
		$item->option (0, 'Выберите');
		
		while (list($friend, $uname) = $db->fetch_row ($get)) {
			
			($_GET['to'] == $friend && $_GET['to'] == $friend)
				? $item->option ($friend, $uname, true)
				: $item->option ($friend, $uname);
				
		}
	}
	else $item->option (0, 'У Вас нет друзей :(');
	
	$item->done ();
	
	
	$item = $form->new_item ('text', true);
	$item->label ('Заголовок');
	$item->name ('header');
	$item->value ($title);
	if (isset ($errors['header'])) $item->error ($errors['header']);
	$item->done ();
	
	$item = $form->new_item ('textarea', true);
	$item->name ('body');
	$item->help ('Использование html-тегов запрещено.');
	if (isset ($errors['body'])) $item->error ($errors['body']);
	$item->done ();
	
	$form->add_button ('submit', 'отправить', 'submit');
	
	$form->past ();
	
	unset ($item, $form);
}

function print_friends ($id) {
	global $db;
	
	$get = $db->query ("SELECT friend, f.user_name FROM ".DB_PEREFIX."_friends AS u
		LEFT JOIN (SELECT user_id, user_name FROM ".DB_PEREFIX."_users) AS f ON f.user_id = u.friend
		WHERE user = ".User::$properties['user_id']." ORDER BY f.user_name");

	if ($db->num_rows ($get) > 0) {
	
		$return = '<option value="0">выберите</option>';
		
		while (list($friend, $uname) = $db->fetch_row ($get)) {
			
			if ($_GET['to'] == $friend)
				$string .= "<option value=\"$friend\" selected>$uname</option>\n";
			else
				$string .= "<option value=\"$friend\">$uname</option>\n";
				
		}
		return $string;
	}
	else return '<option value="0">у Вас нет друзей :(</option>';
}
function isset_friend ($id) {
	global $db;
	
	if ($db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_friends WHERE user = ".User::$properties['user_id']." AND friend = ".$id)) == 1) return true;
	
	return false;
}

